<template>
    <div class="imagery-loader">
        <h3>影像数据加载</h3>
        <div class="imagery-info">
            <p><strong>说明：</strong>影像地图是Cesium的"外衣"，支持多种地图服务</p>
            <p>包括ArcGIS、Mapbox、天地图、高德、百度等在线服务</p>
        </div>
        
        <!-- 服务地址输入 -->
        <div class="imagery-controls">
            <div class="service-url-section">
                <label>服务地址</label>
                <textarea v-model="serveUrl" rows="3" placeholder="请输入或选择影像服务地址"></textarea>
            </div>
            
            <div class="service-name-section">
                <label>影像名称</label>
                <input type="text" v-model="imageName" placeholder="请输入影像名称">
            </div>
            
            <!-- Token输入（如果需要） -->
            <div class="token-section" v-show="isShowToken.length > 1">
                <label>{{ isShowToken }}</label>
                <input type="text" v-model="tokenValue" placeholder="请输入Token值">
            </div>
        </div>
        
        <!-- 在线影像服务列表 -->
        <div class="imagery-services">
            <h4>在线影像服务</h4>
            <div class="services-grid">
                <div v-for="(item, index) in imageList" :key="index" 
                     class="service-item" 
                     :class="{ 'service-selected': selectedServiceIndex === index }"
                     @click="selectService(item, index)">
                    <div class="service-preview">
                        <img :src="getServiceImage(item.cnname)" :alt="item.cnname" />
                        <div class="service-overlay" v-show="hoveredServiceIndex === index">
                            <span>{{ getServiceName(item.cnname) }}</span>
                        </div>
                    </div>
                    <div class="service-name" 
                         @mouseenter="hoveredServiceIndex = index"
                         @mouseleave="hoveredServiceIndex = undefined">
                        {{ getServiceName(item.cnname) }}
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="imagery-actions">
            <button @click="loadImagery" class="load-btn" :disabled="!serveUrl">
                加载影像
            </button>
            <button @click="clearImagery" class="clear-btn">
                清除影像
            </button>
        </div>
        
        <!-- 状态显示 -->
        <div class="imagery-status">
            <p>影像状态: <span :class="imageryStatusClass">{{ imageryStatus }}</span></p>
            <p>图层数量: <span :class="layerCountClass">{{ layerCount }}</span></p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, inject, onMounted } from 'vue';
import { XbsjEarthUi } from '../../../../scripts/xbsjEarthUi';
import { SceneTree } from 'xbsj-xe2/dist-node/xe2';
import { ESImageryLayer } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import { Message } from "earthsdk-ui";
import { searchMaxZindex, getsceneObjNumfromSceneTree } from '../../../../scripts/general';
import { imageData } from './imageData';
import transform from '../../../images/imgdatasource/imageryLocale';

const sceneTree = inject('sceneTree') as SceneTree;
const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi;

// 响应式数据
const imageryStatus = ref('未加载');
const imageryStatusClass = ref('status-unknown');
const layerCount = ref(0);
const layerCountClass = ref('status-unknown');

const serveUrl = ref('');
const imageName = ref('未命名影像');
const tokenValue = ref('');
const isShowToken = ref('');
const imageList = ref<any[]>([]);
const selectedServiceIndex = ref(-1);
const hoveredServiceIndex = ref();

const { zh, image }: any = transform;

// 获取服务名称
const getServiceName = (cnname: string) => {
    return zh[cnname] || cnname;
};

// 获取服务图片
const getServiceImage = (cnname: string) => {
    return image[cnname] || '';
};

// 选择服务
const selectService = (item: any, index: number) => {
    serveUrl.value = item.url;
    imageName.value = getServiceName(item.cnname);
    selectedServiceIndex.value = index;
    isShowToken.value = item.requireField || '';
    
};

// 加载影像
const loadImagery = () => {
    if (!serveUrl.value) {
        Message.error('请选择或输入服务地址');
        return;
    }

    if (isShowToken.value.length > 1 && !tokenValue.value) {
        Message.error('请输入Token值');
        return;
    }

    try {
        imageryStatus.value = '加载中...';
        imageryStatusClass.value = 'status-loading';

        // 获取最大zIndex
        const maxZindex = searchMaxZindex(sceneTree, 'ESImageryLayer');
        
        // 获取或创建影像图层管理文件夹
        let imageryFolder = getOrCreateImageryFolder();
        
        // 创建新的影像图层树项
        const newTreeItem = sceneTree.createSceneObjectTreeItem('ESImageryLayer', undefined, imageryFolder, 'Inner');
        
        if (!newTreeItem) {
            throw new Error('无法创建影像图层');
        }
        
        // 设置选中状态
        sceneTree.uiTree.clearAllSelectedItems();
        newTreeItem.uiTreeObject.selected = true;
        
        if (!newTreeItem.sceneObject) {
            throw new Error('场景对象不存在');
        }
        
        if (newTreeItem.sceneObject.typeName !== 'ESImageryLayer') {
            throw new Error('场景对象类型错误');
        }
        
        const sceneObject = newTreeItem.sceneObject as unknown as ESImageryLayer;
        xbsjEarthUi.propSceneTree = newTreeItem;
        
        // 获取对象编号
        const objNum = getsceneObjNumfromSceneTree(xbsjEarthUi, 'ESImageryLayer');
        
        // 设置图层属性
        newTreeItem.name = (imageName.value === '' ? '未命名影像' : imageName.value) + objNum;
        
        // 设置服务URL
        if (isShowToken.value.length > 1) {
            sceneObject.url = `${serveUrl.value}&${isShowToken.value}=${tokenValue.value}`;
        } else {
            sceneObject.url = serveUrl.value;
        }
        
        sceneObject.zIndex = maxZindex + 1;
        sceneObject.rectangle = [-180, -90, 180, 90];
        
        // 更新状态
        imageryStatus.value = '加载成功';
        imageryStatusClass.value = 'status-success';
        layerCount.value = objNum + 1;
        layerCountClass.value = 'status-success';

        // 清空Token
        tokenValue.value = '';
        
    } catch (error) {
        console.error('加载影像失败:', error);
        imageryStatus.value = '加载失败';
        imageryStatusClass.value = 'status-error';
        Message.error('加载影像失败: ' + (error as Error).message);
    }
};

// 获取或创建影像图层管理文件夹
const getOrCreateImageryFolder = () => {
    const sceneTree = xbsjEarthUi.getSceneTree();
    if (!sceneTree) {
        throw new Error('场景树不可用');
    }

    // 查找是否已存在影像图层管理文件夹（查找真正的SceneTreeItem对象）
    const findImageryFolderTreeItem = (): any => {
        // 遍历场景树的所有根级子项
        if (sceneTree.root.children) {
            for (const child of sceneTree.root.children) {
                if ((child as any).name === '影像数据加载') {
                    return child;
                }
            }
        }
        return null;
    };

    let imageryFolder = findImageryFolderTreeItem();

    // 如果不存在，创建新的影像图层管理文件夹
    if (!imageryFolder) {
        // 参考SceneTree.vue的addNewTreeItem函数，在根级别创建文件夹
        imageryFolder = sceneTree.createGroupTreeItem(undefined, undefined, undefined, undefined);
        if (!imageryFolder) {
            throw new Error('无法创建影像图层管理文件夹');
        }
        // 设置文件夹名称
        imageryFolder.name = '影像数据加载';
    }

    return imageryFolder;
};

// 清除影像
const clearImagery = () => {
    try {
        // 获取场景树
        const sceneTree = xbsjEarthUi.getSceneTree();
        if (!sceneTree) {
            console.error('场景树不可用');
            imageryStatus.value = '场景树不可用';
            imageryStatusClass.value = 'status-error';
            return;
        }

        // 查找影像图层管理文件夹（查找真正的SceneTreeItem对象）
        const findImageryFolderTreeItem = (): any => {
            // 遍历场景树的所有根级子项
            if (sceneTree.root.children) {
                for (const child of sceneTree.root.children) {
                    if ((child as any).name === '影像数据加载') {
                        return child;
                    }
                }
            }
            return null;
        };

        let imageryFolder = findImageryFolderTreeItem();

        if (imageryFolder) {
            // 删除整个影像图层管理文件夹
            try {
                if (typeof imageryFolder.isDestroyed === 'function') {
                    if (!imageryFolder.isDestroyed()) {
                        imageryFolder.detachFromParent();
                    }
                } else if (typeof imageryFolder.isDestroyed === 'boolean') {
                    if (!imageryFolder.isDestroyed) {
                        imageryFolder.detachFromParent();
                    }
                } else {
                    imageryFolder.detachFromParent();
                }
            } catch (folderError) {
                console.warn('删除影像图层管理文件夹失败:', folderError);
            }
        }

        // 更新状态
        imageryStatus.value = '已清除';
        imageryStatusClass.value = 'status-cleared';
        layerCount.value = 0;
        layerCountClass.value = 'status-cleared';
    } catch (error) {
        console.error('清除影像失败:', error);
        imageryStatus.value = '清除失败';
        imageryStatusClass.value = 'status-error';
        Message.error('清除影像失败');
    }
};

// 组件挂载时加载影像服务列表
onMounted(() => {
    try {
        // 使用本地静态数据
        imageList.value = imageData;
        
        // 检查Viewer状态
        if (sceneTree) {
            imageryStatus.value = '就绪';
            imageryStatusClass.value = 'status-ready';
            layerCount.value = getsceneObjNumfromSceneTree(xbsjEarthUi, 'ESImageryLayer');
            layerCountClass.value = 'status-ready';
        } else {
            imageryStatus.value = 'SceneTree不可用';
            imageryStatusClass.value = 'status-error';
        }
    } catch (error) {
        console.error('加载影像服务列表失败:', error);
        imageryStatus.value = '服务列表加载失败';
        imageryStatusClass.value = 'status-error';
    }
});
</script>

<style scoped>
.imagery-loader {
    width: 277px;
    box-sizing: border-box;
    padding: 15px;
    background-color: #1a1a1a;
    border-radius: 8px;
}

.imagery-info {
    padding: 12px;
    background-color: #2a2a2a;
    border-radius: 6px;
    margin-bottom: 15px;
    font-size: 14px;
    color: #e0e0e0;
}

.imagery-controls {
    margin-bottom: 20px;
}

.service-url-section,
.service-name-section,
.token-section {
    margin-bottom: 12px;
}

.service-url-section label,
.service-name-section label,
.token-section label {
    display: block;
    margin-bottom: 6px;
    font-weight: bold;
    color: #e0e0e0;
}

.service-url-section textarea,
.service-name-section input,
.token-section input {
    width: 100%;
    padding: 8px;
    border: 1px solid #444;
    border-radius: 4px;
    background-color: #333;
    color: #e0e0e0;
    font-size: 14px;
    box-sizing: border-box;
}

.service-url-section textarea {
    resize: vertical;
    min-height: 60px;
}

.imagery-services {
    margin-bottom: 20px;
}

.imagery-services h4 {
    margin-bottom: 12px;
    color: #e0e0e0;
    font-size: 16px;
}

.services-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    max-height: 200px;
    overflow-y: auto;
}

.service-item {
    cursor: pointer;
    border: 2px solid transparent;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.service-item:hover {
    border-color: #4CAF50;
}

.service-selected {
    border-color: #2196F3 !important;
    background-color: rgba(33, 150, 243, 0.1);
}

.service-preview {
    position: relative;
    width: 100%;
    height: 60px;
    overflow: hidden;
    border-radius: 4px;
}

.service-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.service-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 12px;
    text-align: center;
}

.service-name {
    padding: 4px;
    font-size: 12px;
    color: #e0e0e0;
    text-align: center;
    word-break: break-all;
}

.imagery-actions {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}

.load-btn,
.clear-btn {
    flex: 1;
    padding: 10px 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
    transition: all 0.3s ease;
}

.load-btn {
    background-color: #4CAF50;
    color: white;
}

.load-btn:hover:not(:disabled) {
    background-color: #45a049;
}

.load-btn:disabled {
    background-color: #666;
    cursor: not-allowed;
}

.clear-btn {
    background-color: #f44336;
    color: white;
}

.clear-btn:hover {
    background-color: #da190b;
}

.imagery-status {
    padding: 12px;
    background-color: #2a2a2a;
    border-radius: 6px;
    border-left: 4px solid #dee2e6;
    font-size: 14px;
    color: #e0e0e0;
}

.status-unknown {
    color: #6c757d;
}

.status-ready {
    color: #17a2b8;
    font-weight: bold;
}

.status-loading {
    color: #ffc107;
    font-weight: bold;
}

.status-success {
    color: #28a745;
    font-weight: bold;
}

.status-error {
    color: #dc3545;
    font-weight: bold;
}

.status-cleared {
    color: #6c757d;
    font-weight: bold;
}

/* 滚动条样式 */
.services-grid::-webkit-scrollbar {
    width: 6px;
}

.services-grid::-webkit-scrollbar-track {
    background: #333;
    border-radius: 3px;
}

.services-grid::-webkit-scrollbar-thumb {
    background: #666;
    border-radius: 3px;
}

.services-grid::-webkit-scrollbar-thumb:hover {
    background: #888;
}
</style>